﻿using Koala.Pro.CodeGenerator.UI.Common;
using System.Text;
using WeifenLuo.WinFormsUI.Docking;

namespace Koala.Pro.CodeGenerator.UI
{
    public partial class FrmCode : DockContent
    {
        public FrmCode()
        {
            InitializeComponent();
            AddDynamicMenuItem();
            SetEditorSetting();
        }

        private void AddDynamicMenuItem()
        {
            string[] codeFormatType = FormatCodeHelper.CodeFormatType;
            foreach (string text in codeFormatType)
            {
                ToolStripMenuItem toolStripMenuItem = new ToolStripMenuItem(text);
                toolStripMenuItem.Click += menu_ChangeFormat_Click; ;
                menu_ChangeFormat.DropDownItems.Add(toolStripMenuItem);
            }
        }

        private void SetEditorSetting()
        {
            txtCodeEditor.ShowEOLMarkers = false;
            txtCodeEditor.ShowInvalidLines = false;
            txtCodeEditor.ShowSpaces = false;
            txtCodeEditor.ShowTabs = false;
            txtCodeEditor.Encoding = Encoding.Default;
            txtCodeEditor.SetHighlighting(FormatCodeHelper.CSHARP);
        }

        private void menu_SaveFile_Click(object sender, EventArgs e)
        {
            var saveFileDialog = new SaveFileDialog();
            saveFileDialog.InitialDirectory = Directory.GetCurrentDirectory();
            saveFileDialog.FileName = Text;
            saveFileDialog.Filter = "txt files (*.txt)|*.txt|CSharp files (*.cs)|*.cs|All files (*.*)|*.*";
            if (DialogResult.OK == saveFileDialog.ShowDialog() && saveFileDialog.FileName.Length > 0)
            {
                txtCodeEditor.SaveFile(saveFileDialog.FileName);
                MessageUtil.ShowTips("保存成功");
            }
        }

        private void menu_CloseAll_Click(object sender, EventArgs e)
        {
            Program.global.CloseAllDocuments();
        }

        private void menu_ChangeFormat_Click(object sender, EventArgs e)
        {
            string type = ((ToolStripMenuItem)sender).Text;
            string text = txtCodeEditor.Text;
            FormatCodeHelper.FormatText(txtCodeEditor, type, text);
        }
    }
}
